package com.changdu.seatunnel.admin.config.model;

import java.io.Serializable;

import org.slf4j.MDC;

import com.changdu.seatunnel.admin.config.common.BusinessException;
import com.changdu.seatunnel.admin.config.common.ExceptionInterface;
import com.changdu.seatunnel.admin.config.enums.HttpResponseStatus;

import lombok.Data;

@Data
public class ResultResponse<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int code;
    
    private String msg;
    
    private T data;
    
    public String getTraceId() {
        return MDC.get("traceId");
    }

    public static <T> ResultResponse<T> success(T result) {
        ResultResponse<T> response = new ResultResponse<T>();
        response.setData(result);
        response.setMsg(HttpResponseStatus.OK.getReasonPhrase());
        response.setCode(HttpResponseStatus.OK.value());
        return response;
    }

    public static <T> ResultResponse<T> error(String message) {
        ResultResponse<T> response = new ResultResponse<T>();
        response.setData(null);
        response.setMsg(message);
        response.setCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.value());
        return response;
    }

    public static <T> ResultResponse<T> error(int code, String message) {
        ResultResponse<T> response = new ResultResponse<T>();
        response.setData(null);
        response.setMsg(message);
        response.setCode(code);
        return response;
    }    
    
    public static <T> ResultResponse<T> error(Exception e) {
        ResultResponse<T> response = new ResultResponse<T>();
        response.setData(null);
        if (e instanceof IllegalArgumentException) {
            response.setMsg(e.getMessage());
            response.setCode(HttpResponseStatus.BAD_REQUEST.value());
        } else if (e instanceof BusinessException) {
        	BusinessException business = (BusinessException) e;
        	response.setCode(business.getCode());
            response.setMsg(e.getMessage());
        } else {
            response.setCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.value());
            response.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 枚举返回
     * @param <T>
     * @param exp
     * @return
     */
    public static <T> ResultResponse<T> error(ExceptionInterface exp) {
        ResultResponse<T> response = new ResultResponse<T>();
        response.setData(null);
        response.setMsg(exp.getMessage());
        response.setCode(exp.getCode());
        return response;
    }
    
}

